package com.example.wwww.controller;

import com.example.wwww.model.Dish;
import com.example.wwww.repo.InMemoryStore;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/dishes")
public class DishController {
    private final InMemoryStore store;
    public DishController(InMemoryStore store) { this.store = store; }

    @GetMapping
    public List<Dish> list(@RequestParam(value = "merchantId", required = false) Long merchantId) {
        return merchantId == null ? store.getDishes() : store.getDishesByMerchant(merchantId);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Dish> get(@PathVariable Long id) {
        return store.getDishById(id).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public Dish create(@RequestBody Dish dish) { return store.addDish(dish); }

    @PutMapping("/{id}")
    public ResponseEntity<Dish> update(@PathVariable Long id, @RequestBody Dish updates) {
        Dish updated = store.updateDish(id, updates);
        return updated == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(updated);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        boolean ok = store.deleteDish(id);
        return ok ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }
}


